import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref({
    id: '',
    username: '',
    nickname: '',
    avatar: '',
    token: ''
  })

  const isLoggedIn = computed(() => !!userInfo.value.token)

  // 动作
  const login = async loginData => {
    try {
      // 这里应该调用登录API
      // const result = await userApi.login(loginData)

      // 模拟登录成功
      const mockUser = {
        id: '123',
        username: loginData.username,
        nickname: '用户昵称',
        avatar: 'https://via.placeholder.com/100',
        token: 'mock-token-' + Date.now()
      }

      userInfo.value = mockUser

      // 保存到本地存储
      uni.setStorageSync('userInfo', mockUser)
      uni.setStorageSync('token', mockUser.token)

      return mockUser
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  const logout = () => {
    userInfo.value = {
      id: '',
      username: '',
      nickname: '',
      avatar: '',
      token: ''
    }

    // 清除本地存储
    uni.removeStorageSync('userInfo')
    uni.removeStorageSync('token')
  }

  const updateUserInfo = newUserInfo => {
    userInfo.value = { ...userInfo.value, ...newUserInfo }
    uni.setStorageSync('userInfo', userInfo.value)
  }

  const initUserInfo = () => {
    const savedUserInfo = uni.getStorageSync('userInfo')
    const savedToken = uni.getStorageSync('token')

    if (savedUserInfo && savedToken) {
      userInfo.value = savedUserInfo
    }
  }

  return {
    // 状态
    userInfo,
    isLoggedIn,

    // 动作
    login,
    logout,
    updateUserInfo,
    initUserInfo
  }
})
